import { resetPasswordApi } from '@/api/manager'
import { showModal, toast } from '@/utils'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

export function useManager() {
  const router = useRouter()
  const store = useStore()
  const formRef = ref(null)
  const formDrawerRef = ref(null)

  // 修改密码
  const form = reactive({
    oldpassword: '',
    password: '',
    repassword: '',
  })

  const validatePass = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('输入不能为空！'))
    } else if (value !== form.password) {
      callback(new Error('两次输入密码不一致'))
    } else {
      callback()
    }
  }

  const rules = {
    oldpassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    repassword: [
      { required: true, message: '请再次输入新密码', trigger: 'change' },
      { validator: validatePass, trigger: 'change' },
    ],
  }

  const openRePasswordForm = () => formDrawerRef.value?.open()
  function confirmClick() {
    formRef.value.validate((valid, fields) => {
      if (!valid) {
        return
      } else {
        formDrawerRef.value.showLoading()
        resetPasswordApi(form)
          .then((res) => {
            toast('修改密码成功，请重新登录')
            store.dispatch('logoutAction')
            router.push({ path: '/login' })
          })
          .finally(() => {
            formDrawerRef.value.hideLoading()
          })
      }
    })
  }

  return {
    form,
    formRef,
    validatePass,
    rules,
    confirmClick,
    formDrawerRef,
    openRePasswordForm,
  }
}

export function useLogout() {
  // router，store要放在use函数里面，放在外面会有警告
  const router = useRouter()
  const store = useStore()

  function logout() {
    showModal('提示', 'warning', '是否退出登录').then((res) => {
      store.dispatch('logoutAction').then((res) => {
        toast('退出登录成功')
        router.push('/login')
      })
    })
  }

  return {
    logout,
  }
}
